package main

import "fmt"

func main() {
	s := "Let's take LeetCode contest"
	fmt.Printf(reverseWords(s))
	fmt.Printf(reverseWords1(s))
}

func reverseWords(s string) string {
	if len(s) < 1 {
		return ""
	}
	res := ""
	tem_s := ""
	for i := 0; i < len(s); i++ {
		if string(s[i]) == " " {
			res += reverseString(tem_s) + " "
			tem_s = ""
		} else {
			tem_s += string(s[i])
		}
	}
	return res + reverseString(tem_s)
}

// 反转字符串
func reverseString(s string) string {
	runes := []rune(s)
	for from, to := 0, len(runes)-1; from < to; from, to = from+1, to-1 {
		runes[from], runes[to] = runes[to], runes[from]
	}
	return string(runes)
}

//官方题解

func reverseWords1(s string) string {
	length := len(s)
	ret := []byte{}
	for i := 0; i < length; {
		start := i
		for i < length && s[i] != ' ' {
			i++
		}
		for p := start; p < i; p++ {
			ret = append(ret, s[start+i-1-p])
		}
		for i < length && s[i] == ' ' {
			i++
			ret = append(ret, ' ')
		}
	}
	return string(ret)
}
